// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { cloudHelper, pageHelper, timeHelper, validate } = pathImport;;

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isEdit: false,
		isAdmin: false,

		content: '',

		curIdx: 0,
		isScrollLower: false,

		imgList: [],

		state: 1 // 通过
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');

		if (!pageHelper.getOptions(this, options)) return;

		if (options && options.flag == 'admin') {
			this.setData({ isAdmin: true, isEdit: true });
		}

		if (!pageHelper.getOptions(this, options, 'flag')) return;

		if (!await PassportBiz.loginMustBackWin(this)) return;

		this.setData(FlowBiz.initFormStepData(this.data.id)); // 初始化表单数据  

		await this._loadDetail();

		if (this.data.flow.FLOW_STATUS == 1) {
			// 待审批
			wx.setNavigationBarTitle({
				title: this.data.flow.FLOW_TO_NATIVE_DEPT + ' - 审批',
			});

		}
		else if (this.data.flow.FLOW_STATUS == 8) {
			// 驳回
			wx.setNavigationBarTitle({
				title: this.data.flow.FLOW_NOW_NATIVE_DEPT + ' - 审批',
			});
		}
		else if (this.data.flow.FLOW_STATUS == 9) {
			// 驳回
			wx.setNavigationBarTitle({
				title: '审批完成',
			});
		}

		// 当前审批部门
		if (this.data.flag == 'edit') {
			this.setData({ nowDept: this.data.flow.FLOW_NOW_NATIVE_DEPT + ' - 修改审批意见' });
		}
		else {
			this.setData({ nowDept: this.data.flow.FLOW_TO_NATIVE_DEPT });
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		// 每次显示页面时强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');

		await this._loadDetail();
		wx.stopPullDownRefresh();
	},

	bindOpenFileTap: function (e) {
		FlowBiz.openFlowFile(e, this);
	},

	bindCheckTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');
		
		pageHelper.showAction(this, [
			{
				name: '通过',
				class: 'collection text-green',
				action: 'check',
				params: { flag: 1 }
			},
			{
				name: '不通过',
				class: 'card text-red',
				action: 'check',
				params: { flag: 0 }
			},
			{
				name: '取消',
				class: 'text-gray',
				action: 'cancel'
			}
		]);
	},

	bindSubmitCmpt: async function (e) {
		if (!await PassportBiz.loginMustCancelWin(this)) return;

		let forms = e.detail;

		let callback = async () => {
			try {
				let opts = {
					title: '提交中'
				}
				let params = {
					id: this.data.id,
					flag: this.data.flag,
					state: this.data.state,
					forms,
				}

				await cloudHelper.callCloudSumbit('flow/step', params, opts).then(async res => { 

					let cb = () => {
						PublicBiz.removeCacheList('my-flow-checked');
						PublicBiz.removeCacheList('my-flow-checking');
						PublicBiz.removeCacheList('my-flow-list');

						wx.navigateBack();

					}
					if (this.data.state == 1) {
						if (res.data.dept)
							pageHelper.showModal('审批意见已提交，待 [' + res.data.dept + '] 处理', '温馨提示', cb);
						else
							pageHelper.showModal('审批通过，本申请审批流程全部完成！', '温馨提示', cb);
					}
					else if (this.data.state == 8)
						pageHelper.showModal('提交成功，该申请已经做驳回处理~', '温馨提示', cb);
				});

			} catch (err) {
				console.log(err);
			};
		}

		let cb = () => {
			wx.requestSubscribeMessage({
				tmplIds: [projectSetting.NOTICE_TEMP_NEW_FLOW, projectSetting.NOTICE_TEMP_RESULT_FLOW],
				async complete() {
					callback();
				}
			});
		}

		pageHelper.showConfirm('确认提交？', cb);
	},

	url: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');
		
		pageHelper.url(e, this);
	},

	model: function (e) {
		pageHelper.model(this, e);
	},

	_loadDetail: async function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');
		
		let id = this.data.id;
		if (!id) return;

		let params = {
			id,
		};
		let opt = {
			title: 'bar'
		};
		let steps = await cloudHelper.callCloudData('flow/step_all', params, opt);
		if (!steps || !Array.isArray(steps))
			steps = [];

		this.setData({
			steps
		});
	},

	bindDelTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');
		
		let cb = async () => {
			try {
				let params = {
					id: this.data.id
				}
				let opt = {
					title: '删除中',
				}
				await cloudHelper.callCloudData('flow/del', params, opt);
				await pageHelper.showSuccToast('删除成功');
				wx.navigateBack();

			} catch (err) {
				console.log(err);
			}
		}
		pageHelper.showConfirm('确认删除? 操作不可恢复', cb);
	},

	_setContentDesc: function () {
		if (!this.data.content) return;
		
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_step');

		wx.showLoading({ title: '处理中' });
		wx.hideLoading();
	},

	bindImgUploadTap: function (e) {
		let that = this;
		wx.chooseImage({
			count: 4, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: async function (res) {
				that.setData({
					imgList: that.data.imgList.concat(res.tempFilePaths)
				});
			}
		});
	},

	bindDelImgTap: function (e) {
		let that = this;
		let idx = pageHelper.dataset(e, 'idx');
		let imgList = that.data.imgList;
		imgList.splice(idx, 1);
		that.setData({
			imgList
		})
	},

	bindPreviewImgTap: function (e) {
		let that = this;
		let idx = pageHelper.dataset(e, 'idx');
		let urls = that.data.imgList;

		wx.previewImage({
			current: urls[idx],
			urls
		});
	},

	bindScrollLower: function () {
		if (!this.data.isScrollLower) {
			this.setData({
				isScrollLower: true
			})
		}
	},

	bindScrollUpper: function () {
		if (this.data.isScrollLower) {
			this.setData({
				isScrollLower: false
			})
		}
	},

	bindRightTab: function (e) {
		let idx = pageHelper.dataset(e, 'idx');
		if (!this.data.steps || !this.data.steps[idx]) return;
		this.setData({
			content: this.data.steps[idx].FLOW_STEP_CONTENT,
			curIdx: idx
		}); 
	},

	bindCheckCmpt: async function (e) {
		try {
			// 强制设置登录状态
			FlowBiz.forceSetLoginState(this, 'flow_step');
			
			let params = {
				id: this.data.id,
				idx: this.data.curIdx,
				isAgree: Number(pageHelper.dataset(e, 'flag')),
				content: this.data.content
			}

			if (params.isAgree && !params.content)
				return pageHelper.showNoneToast('请先填写审批意见');

			if (!params.isAgree && !params.content)
				return pageHelper.showNoneToast('请先填写不通过理由');

			if (!validate.checkTextLength(params.content, 1, 60000))
				return pageHelper.showNoneToast('意见范围1-60000个字符');

			let imgList = this.data.imgList;
			let userImgs = [];
			for (let k = 0; k < imgList.length; k++) {
				let path = imgList[k];
				let ext = path.match(/\.[^.]+?$/)[0];
				let cloudPath = pageHelper.genRandomAlpha(20) + ext; 

				// 上传图片
				wx.showLoading({
					title: '上传中' + (k + 1) + '/' + imgList.length,
					mask: true
				});
				let res = await cloudHelper.transTempPicOne(path, cloudPath);

				userImgs.push(res.cloudID); 
			}
			params.img = userImgs; 

			let opts = {
				title: params.isAgree ? '通过中' : '不通过处理中',
			}

			await cloudHelper.callCloudData('flow/step_check', params, opts);
			await pageHelper.showSuccToast('处理成功');

			wx.redirectTo({
				url: pageHelper.fmtURLByPID('/pages/flow/detail/flow_detail?id=' + this.data.id),
			});
		}
		catch (err) {
			console.log(err);
		}
	}
})